﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using General.Core.Data;
using Microsoft.AspNetCore.Mvc;
using General.Entities.Models;
using General.Framework;
using General.Entities.ViewData.Admin;
using General.Mvc.Filters;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using General.Services.SystemConfig;
using General.Entities.ViewData.Chat;
using General.Services.Admin;
using Microsoft.AspNetCore.Hosting;
using System.IO;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace General.Mvc.Controllers
{
    [Route("api/app/v1/user/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class UserController : Controller
    {
        private readonly IRepository<tc_sysconfig> tc_SysconfigRepository;
        private readonly IRepository<tc_user> tc_UserRepository;
        private readonly ISystemConfigService systemConfigService;
        private readonly IAdminService adminService;

        public UserController(IRepository<tc_sysconfig> tc_sysconfigRepository,
            IRepository<tc_user> tc_userRepository,
            ISystemConfigService systemConfigService,
            IAdminService adminService)
        {
            tc_SysconfigRepository = tc_sysconfigRepository;
            tc_UserRepository = tc_userRepository;
            this.systemConfigService = systemConfigService;
            this.adminService = adminService;
        }


        /// <summary>
        /// 用户上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserCheckFilter]
        public async Task<IActionResult> UploadPhoto([FromServices] IWebHostEnvironment environment)
        {
            AjaxResult state = new AjaxResult();
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { state.code = 0; state.message = "请选择上传的文件。"; return Json(state); }
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = "/" + DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            if (!Directory.Exists(webRootPath + "/upload/photo" + timedir))
            {
                Directory.CreateDirectory(webRootPath + "/upload/photo" + timedir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload/photo"+ timedir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }
            string strpath = Path.Combine("upload/photo"+ timedir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }

            state.code = AjaxResultStateEnum.Ok;
            state.message = "上传成功";
            state.data = "/"+strpath;
            return Json(state);
        }

        /// <summary>
        /// 创建聊天用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateUser([FromForm]string token)
        {
            AjaxResult result = new AjaxResult();
            var userid = await RedisHelper.GetAsync("token"+token);
            var savedaymodel = await systemConfigService.GetConfigInfoByCode("usersavetime");
            var savedayval = Convert.ToInt32(savedaymodel.value);
            if (!string.IsNullOrEmpty(userid))
            {
                //var user = await tc_UserRepository.getByIdAsync(userid);
                
            }
            else
            {
                var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Connection.RemoteIpAddress.ToString();
                }
                //创建
                var user = new tc_user()
                {
                     createtime = DateTime.Now, ip = ip.Replace("::ffff:", ""), isread = 0, ismsg = 0, lasttime = DateTime.Now, noreadnum = 0, userimg = "/images/user.png", username = "访客"+ StringExtension.GenerateRandomNumber(6)
                };

                await tc_UserRepository.insertAsync(user);

                token = Guid.NewGuid().ToString();
                await RedisHelper.SetAsync("token" + token, user.id.ToString(),60*60*24* savedayval);
                userid = user.id.ToString();
            }

            //配置及时通讯
            var claims = new[]
            {
                    new Claim("uid", userid),
                    new Claim("token",token),
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwttoken = new JwtSecurityToken(JwtSettings.Issuer,
               JwtSettings.Audience, claims,
               expires: DateTime.Now.AddDays(savedayval),
               signingCredentials: creds);
            //约等于明文保存的 claims+签名
            string access_token = new JwtSecurityTokenHandler().WriteToken(jwttoken);

            result.message = token;
            result.data = access_token;
            result.code = AjaxResultStateEnum.Ok;

            return Content(JsonHelper.Serialize(result));
        }


        /// <summary>
        /// 获取聊天群组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserCheckFilter]
        public async Task<IActionResult> GetGroupInfo()
        {
            AjaxResult result = new AjaxResult();
            var token = HttpContext.Request.Headers["Auth"].ToString();
            var userid = await RedisHelper.GetAsync("token" + token);
            ClientGroupModel model = new ClientGroupModel();
            model.chatid = userid;
            //获取管理员信息
            var admin = await adminService.GetInfoById(1);
            //获取用户信息
            var user = await tc_UserRepository.getByIdAsync(Convert.ToInt32(userid));
            model.chatname = admin.username;
            model.chatuser = new List<string>()
            {
                admin.headimg,user.userimg
            };

            return Content(JsonHelper.Serialize(model));
        }


    }
}
